package wechat.rcv.cosuming;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import wechat.rcv.ServiceAppFrontController;
import wechat.rcv.data.WeResponseBuilder;
import wechat.rcv.util.Log4jService;
import windbell.domain.user.BaseUser;
import windbell.domain.user.CCHospitalUserDao;
import windbell.domain.user.CCPlatformUserDAO;
import windbell.domain.user.WeChatUser;
//import windbell.domain.user.CCPlatformUser;
//import windbell.domain.user.CCPlatformUserDAO;
import windbell.domain.user.WechatService;

//import com.industrialpark.domain.CompanyDAO;
//import com.industrialpark.domain.Company;
@Component
public class EventSubscribeConsuming implements IMsgConsuming {
	final static Logger logger = Logger
			.getLogger(ServiceAppFrontController.class.getName());
	private RequestObj req;
//	@Autowired
//	private CompanyDAO companyDAO;
	
	//hospital
	@Autowired
	@Qualifier("windbell.domain.user.WechatService")
	private WechatService wechatService;
	
	@Autowired
	private CCHospitalUserDao cchospitalUserDao;
	
	@Autowired
	private CCPlatformUserDAO ccPlatformUserDAO;
	
	
	@Autowired
	private Log4jService log4jService;
	
	// <xml>
	// <ToUserName><![CDATA[toUser]]></ToUserName>
	// <FromUserName><![CDATA[FromUser]]></FromUserName>
	// <CreateTime>123456789</CreateTime>
	// <MsgType><![CDATA[event]]></MsgType>
	// <Event><![CDATA[subscribe]]></Event>
	// </xml>
	public EventSubscribeConsuming() {
	}

	@Override
	public String acceptSync() {
		String res_str = "欢迎关注****服务号!已有特定用户关注, 您不能收到推送消息!";
		boolean mock = false;
		String openId = req.getFromUserName();
		
		if (mock) {
			addWechatUser("111" , "oQ19TwZ26yGx3Fvu4rAld1LvuWqI");
			logger.info("Mock =======>weixin has been added");
		} else {
			if (req.getEventKey() != null && !"".equals(req.getEventKey())) {
				log4jService.info(EventSubscribeConsuming.class,"Subscribe =====> code = "+req.getEventKey());
				// res_str += "\ncustomer code is "+
				// req.getEventKey().substring("qrscene_".length());
				
				String userCode = req.getEventKey().substring("qrscene_".length());
				
				
				
				logger.info("=================> rev " + res_str);
				
				if (addWechatUser(userCode,openId)){
					logger.info("===================> found in db");
					try {
						BaseUser huser = wechatService.getUserbyWechatId(openId);
						if (huser != null) {
							logger.info("=================> huser " + huser.getName());
							String name = huser.getName();
							res_str = name + ", 欢迎加入****服务号!您将收到推送消息!";
						} else {
							logger.info("=================> huser null");
						}
					} catch(Exception e) {
						logger.info("===============================>Exception: " + e.toString());
					}
					
					
//					String name = userDao.findByUserId(userCode).getName();
//					String name = companyDAO.findByCode(companycode).getName();
//					res_str = name + ", 欢迎加入****服务号!您将收到推送消息!";
				}
			}
			else{
				res_str = "未知名称" + ", 欢迎加入****服务号!您将收到推送消息!";
			}
		}
		// res_str += "\n"+"FromUser is "+ req.getFromUserName();
		logger.info("===================> 11111111");
		log4jService.info(EventSubscribeConsuming.class,"FromUser = "+ openId);		
		logger.info("===================> 222222222");
		return WeResponseBuilder.createTxtMsg(openId,
				req.getToUserName(), res_str);
	}

	@Override
	public String acceptAsync() {
		return acceptSync();
	}

	@Override
	public void setRequestObj(RequestObj ro) {
		// TODO Auto-generated method stub
		req = ro;
	}

	private boolean addWechatUser(String usercode, String openid) {
		boolean ret = false;
		try {
			logger.info("***********customercode " + usercode);
			logger.info("***********openid " + openid);
			
			
			BaseUser user = null;
			
			if (cchospitalUserDao.getUserById(usercode) != null) {
				user = cchospitalUserDao.getUserById(usercode);
			} else {
				user = assertNotNull(ccPlatformUserDAO.findByUserId(usercode));
			}
			
			logger.info("===================user name: " + user.getName());
			
			ret = wechatService.hasWechatUser(user);
			if (!ret) {
				logger.info("======================>register wechat user");
				WeChatUser wuser = wechatService.registerWeChatUser(openid, user);
				if (wuser == null) {
					logger.info("====================> wechat user null");
				} else {
					logger.info("====================> wechat user: " + wuser.getWechatid());
				}
				ret = true;
			}
			
//			if (ret=!wechatService.hasWechatUser(user)) {
//				logger.info("======================>register wechat user");
//				WeChatUser wuser = wechatService.registerWeChatUser(openid, user);
//				if (wuser == null) {
//					logger.info("====================> wechat user null");
//				} else {
//					logger.info("====================> wechat user: " + wuser.getWechatid());
//				}
//				
//			}
			
//			Company c = assertNotNull(companyDAO.findByCode(companycode));
//			if (ret=!c.hasWechatUser()){
//				c.registerWeChatUser(openid);
//			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			logger.info("failed to find user by code");
		}
		return ret;
	}
	
	private <T> T assertNotNull(T t) {
		if (t == null)
			throw new RuntimeException();
		return t;
	}
}
